package com.itany.nmms.service.impl;

import com.itany.nmms.constant.StatusConstant;
import com.itany.nmms.dao.StaffMapper;
import com.itany.nmms.entity.Staff;
import com.itany.nmms.entity.StaffExample;
import com.itany.nmms.exception.CodeErrorException;
import com.itany.nmms.exception.RequestParameterErrorException;
import com.itany.nmms.exception.StaffNotExistException;
import com.itany.nmms.factory.ObjectFactory;
import com.itany.nmms.service.StaffService;
import com.itany.nmms.util.MD5Util;
import com.itany.nmms.util.ParameterUtil;

import java.util.List;

/**
 * @Author:石小俊
 * @Date:2023/1/3 16:16
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
public class StaffServiceImpl implements StaffService {
    @Override
    public Staff login(String loginName, String password, String role, String code, String image) throws RequestParameterErrorException, CodeErrorException, StaffNotExistException {
        // 由于SqlSession属于线程单例,在业务结束之后将会关闭
        // 因此,涉及到SqlSession的信息需要在对应的业务方法中进行处理
        // 例如:dao是通过SqlSession获取的,因此,必须在业务方法中获取
        // 事务对象也是通过SqlSession获取的,因此,必须在业务方法中获取
        StaffMapper staffMapper = (StaffMapper) ObjectFactory.getObject("staffMapper");
        // 参数校验
        if(ParameterUtil.isNull(loginName) || ParameterUtil.isNull(password) || ParameterUtil.isNull(role) || ParameterUtil.isNull(code) || ParameterUtil.isNull(image)){
            throw new RequestParameterErrorException("请求参数有误");
        }

        // 判断验证码是否正确
        if(!code.equals(image)){
            throw new CodeErrorException("验证码不正确");
        }

        // 判断账号密码是否正确
        // 此处含有一个隐含条件,员工必须在职才能登陆
        StaffExample example = new StaffExample();
        example.or()
                .andLoginNameEqualTo(loginName)
                .andPasswordEqualTo(MD5Util.md5(password))
                .andRoleEqualTo(role)
                // 必须在职
                .andIsValidEqualTo(StatusConstant.STAFF_ENABLED);
        List<Staff> staffs = staffMapper.selectByExample(example);
        if(staffs.isEmpty()){
            throw new StaffNotExistException("账号或密码错误");
        }
        return staffs.get(0);
    }
}
